package com.fz.song.service;

import cn.hutool.json.JSONUtil;
import com.fz.song.entity.User;
import com.fz.song.mapper.UserMapper;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.AuthorityUtils;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import java.util.ArrayList;


@Service
@Slf4j
public class MyUserDetailsService implements UserDetailsService {

    @Autowired
    UserMapper userMapper;

    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        if (StringUtils.isEmpty(username)) {
            throw new UsernameNotFoundException("用户名不存在");
        }
        User user = userMapper.findUserByUserName(username);
        log.info("查询用户信息:{}", JSONUtil.parse(user));
        if (null == user) {
            throw new UsernameNotFoundException("用户名不存在");
        }
        //自定义执行
        //setAuthRole(user);
        //使用工具类,这种方式只能用逗号,
        user.setAuthorities(AuthorityUtils.commaSeparatedStringToAuthorityList(user.getRoles()));
        return user;
    }

    private void setAuthRole(User user) {

        String roles = user.getRoles();
        String[] split = roles.split(",");

        ArrayList<GrantedAuthority> list = new ArrayList<>();

        for (String str : split) {
            SimpleGrantedAuthority authority = new SimpleGrantedAuthority(str);
            list.add(authority);
        }

    }
}
